/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package co.springtree.spectrum.orm.controller;

import co.springtree.spectrum.orm.controller.exceptions.NonexistentEntityException;
import co.springtree.spectrum.orm.controller.exceptions.PreexistingEntityException;
import co.springtree.spectrum.orm.entities.Command;
import java.io.Serializable;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import co.springtree.spectrum.orm.entities.CommandRule;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;

/**
 *
 * @author Ricardo
 */
public class CommandJpaController implements Serializable {

    public CommandJpaController(EntityManagerFactory emf) {
        this.emf = emf;
    }
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Command command) throws PreexistingEntityException, Exception {
        if (command.getCommandRuleCollection() == null) {
            command.setCommandRuleCollection(new ArrayList<CommandRule>());
        }
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Collection<CommandRule> attachedCommandRuleCollection = new ArrayList<CommandRule>();
            for (CommandRule commandRuleCollectionCommandRuleToAttach : command.getCommandRuleCollection()) {
                commandRuleCollectionCommandRuleToAttach = em.getReference(commandRuleCollectionCommandRuleToAttach.getClass(), commandRuleCollectionCommandRuleToAttach.getCommandruleId());
                attachedCommandRuleCollection.add(commandRuleCollectionCommandRuleToAttach);
            }
            command.setCommandRuleCollection(attachedCommandRuleCollection);
            em.persist(command);
            for (CommandRule commandRuleCollectionCommandRule : command.getCommandRuleCollection()) {
                Command oldCommandIdOfCommandRuleCollectionCommandRule = commandRuleCollectionCommandRule.getCommandId();
                commandRuleCollectionCommandRule.setCommandId(command);
                commandRuleCollectionCommandRule = em.merge(commandRuleCollectionCommandRule);
                if (oldCommandIdOfCommandRuleCollectionCommandRule != null) {
                    oldCommandIdOfCommandRuleCollectionCommandRule.getCommandRuleCollection().remove(commandRuleCollectionCommandRule);
                    oldCommandIdOfCommandRuleCollectionCommandRule = em.merge(oldCommandIdOfCommandRuleCollectionCommandRule);
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            if (findCommand(command.getCommandId()) != null) {
                throw new PreexistingEntityException("Command " + command + " already exists.", ex);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Command command) throws NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Command persistentCommand = em.find(Command.class, command.getCommandId());
            Collection<CommandRule> commandRuleCollectionOld = persistentCommand.getCommandRuleCollection();
            Collection<CommandRule> commandRuleCollectionNew = command.getCommandRuleCollection();
            Collection<CommandRule> attachedCommandRuleCollectionNew = new ArrayList<CommandRule>();
            for (CommandRule commandRuleCollectionNewCommandRuleToAttach : commandRuleCollectionNew) {
                commandRuleCollectionNewCommandRuleToAttach = em.getReference(commandRuleCollectionNewCommandRuleToAttach.getClass(), commandRuleCollectionNewCommandRuleToAttach.getCommandruleId());
                attachedCommandRuleCollectionNew.add(commandRuleCollectionNewCommandRuleToAttach);
            }
            commandRuleCollectionNew = attachedCommandRuleCollectionNew;
            command.setCommandRuleCollection(commandRuleCollectionNew);
            command = em.merge(command);
            for (CommandRule commandRuleCollectionOldCommandRule : commandRuleCollectionOld) {
                if (!commandRuleCollectionNew.contains(commandRuleCollectionOldCommandRule)) {
                    commandRuleCollectionOldCommandRule.setCommandId(null);
                    commandRuleCollectionOldCommandRule = em.merge(commandRuleCollectionOldCommandRule);
                }
            }
            for (CommandRule commandRuleCollectionNewCommandRule : commandRuleCollectionNew) {
                if (!commandRuleCollectionOld.contains(commandRuleCollectionNewCommandRule)) {
                    Command oldCommandIdOfCommandRuleCollectionNewCommandRule = commandRuleCollectionNewCommandRule.getCommandId();
                    commandRuleCollectionNewCommandRule.setCommandId(command);
                    commandRuleCollectionNewCommandRule = em.merge(commandRuleCollectionNewCommandRule);
                    if (oldCommandIdOfCommandRuleCollectionNewCommandRule != null && !oldCommandIdOfCommandRuleCollectionNewCommandRule.equals(command)) {
                        oldCommandIdOfCommandRuleCollectionNewCommandRule.getCommandRuleCollection().remove(commandRuleCollectionNewCommandRule);
                        oldCommandIdOfCommandRuleCollectionNewCommandRule = em.merge(oldCommandIdOfCommandRuleCollectionNewCommandRule);
                    }
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = command.getCommandId();
                if (findCommand(id) == null) {
                    throw new NonexistentEntityException("The command with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Command command;
            try {
                command = em.getReference(Command.class, id);
                command.getCommandId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The command with id " + id + " no longer exists.", enfe);
            }
            Collection<CommandRule> commandRuleCollection = command.getCommandRuleCollection();
            for (CommandRule commandRuleCollectionCommandRule : commandRuleCollection) {
                commandRuleCollectionCommandRule.setCommandId(null);
                commandRuleCollectionCommandRule = em.merge(commandRuleCollectionCommandRule);
            }
            em.remove(command);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Command> findCommandEntities() {
        return findCommandEntities(true, -1, -1);
    }

    public List<Command> findCommandEntities(int maxResults, int firstResult) {
        return findCommandEntities(false, maxResults, firstResult);
    }

    private List<Command> findCommandEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Command.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Command findCommand(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Command.class, id);
        } finally {
            em.close();
        }
    }

    public int getCommandCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Command> rt = cq.from(Command.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
